<?php
// For debugging
include_once 'dBug.php';
// For extracting elements from DOM
require 'simple_html_dom.php';

class xtractor {
	private $source = array();
	private $links = array();
	private $images = array();
	private $url = null;
	
	function __construct($url, $html) {
		if ($this->validate_url($url)) {
			$this->url = $url;
			$this->source['url'] = file_get_html ( $url );
		} else
			echo '<p>URL invalid.</p>';
		
		if (strlen($html) > 0)
			$this->source['html'] = str_get_html ( $html );
		else
			echo '<p>HTML is empty.</p>';
	}
	
	public function get_links() {
		foreach ($this->source as $val) {
			foreach ($val->find('a') as $element) {
				// Making sure that the link has text
				$text = (isset($element->plaintext) && strlen(trim($element->plaintext)) > 0) ?	
					$element->plaintext : htmlspecialchars ( trim($element->href), ENT_QUOTES );
				//Making sure the links are working
				if (!preg_match('/^http(s)?:\/\//i', trim($element->href))) {
					$href = (preg_match('/\/$/', $this->url) || preg_match('/^\//', $element->href)) ?
						$this->url . $element->href : $this->url .'/'.$element->href;
				} else {
					$href = $element->href;
				}
				$li =  "<a href=\"" . $href . "\">" . $text . "</a>";
				array_push($this->links, $li);
			}
		}
		
		return $this->links;
	}
	
	public function get_images() {
		foreach ($this->source as $val) {
			foreach ($val->find('img') as $element) {
				
				if (!preg_match('/^http(s)?:\/\//i', trim($element->src))) {
					$src = (preg_match('/\/$/', $this->url) || preg_match('/^\//', $element->src)) ?
						$this->url . $element->src : $this->url .'/'.$element->src;
				} else {
					$src = $element->src;
				}
				
				$li =  "<img src=\"" . htmlspecialchars ( trim($src), ENT_QUOTES ) . "\" />";
				array_push($this->images, $li);
			}
		}
		
		return $this->images;
	}
	
	private function validate_url($url) {
		// Will check if the url is valid - http/https - Case insencitive
		return preg_match ( '/^http(s)?:\/\/[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(\/.*)?$/i', $url );
	}
}